<?php

namespace app\common\model;

use think\Model;
use think\Session;
use think\Validate;

/**
 * Created by PhpStorm.
 * Author: Masky
 * Date: 2017/11/1
 * Time: 16:20
 */
class ViewBlock extends Model {
	
	const STATUS_CLOSE=0;
	const STATUS_OPEN=1;
	
	public static $status=[
		self::STATUS_CLOSE=>'关闭',
		self::STATUS_OPEN=>'开启'
	];
	public static $position=[
		'shouyebanner'=>[
			'notice'=>'图片尺寸比例为 19:6，推荐尺寸 1900*600'
		],
		'xuanchuanpian'=>[
			'notice'=>'上传视频截图或者添加视频通用链接，尺寸为300*480'
		],'jianjie'=>[
			'notice'=>''
		],'tuji'=>[
			'notice'=>'图片尺寸比例为 1:1，推荐尺寸 320*320'
		],'baodao'=>[
			'notice'=>''
		],'jiabin'=>[
			'notice'=>'图片尺寸比例为 1:1，推荐尺寸 320*320'
		],'pingwei'=>[
			'notice'=>'图片尺寸比例为 1:1，推荐尺寸 320*320'
		],'wanyan'=>[
			'notice'=>'图片尺寸比例为 1:1，推荐尺寸 320*320'
		],'jingcaishipin'=>[
			'notice'=>'上传视频截图，链接为原视频链接'
		],'zanzhushang'=>[
			'notice'=>'图片将会缩放为3:1'
		],'wangqi'=>[
			'notice'=>'图片尺寸比例为 1:1，推荐尺寸 320*320'
		],'youqinglianjie'=>[
			'notice'=>''
		],'zubie'=>[
			'notice'=>''
		]];
	
	public function addVB($input){
		$validate=new Validate(['title'=>'require','position'=>'require']);
		$result=FALSE;
		if($validate->check($input)){
			$input['created_at']=time();
			$result=$this->create($input);
			$result || $this->error="添加失败";
		}else{
			$this->error=$validate->getError();
		}
		return $result;
	}
	
	public function editVB($input){
		$validate=new Validate(['title'=>'require','position'=>'require']);
		$result=FALSE;
		if($validate->check($input)){
			$result=$this->save($input,['id'=>$input['id']]);
			$result || $this->error="编辑失败";
		}else{
			$this->error=$validate->getError();
		}
		return $result;
	}
	
	public function getInfo($condition=[],$field='*',$order='id desc'){
		
		$result=$this->where($condition)->field($field)->order($order)->find();
		$result && $this->formatSelect($result);
		return $result;
	}
	public function getContentByPosition($position){
		$result=$this->where(['position'=>$position])->field("*")->order('id desc')->find();
		if($result){
			$this->formatSelect($result);
			$content=new ViewBlockContent();
			$content_list=$content->where(['vb_id'=>$result['id']])->order("sort desc")->select();
			foreach ($content_list as &$item){
				$content->formatSelect($item);
			}
			$result['content']=$content_list;
		}
		return $result;
	}
	public function formatSelect(&$data){
		$data['created_at_dis']=date("Y-m-d H:i:s",$data['created_at']);
		$data['status_dis']=self::$status[$data['status']];
	}
	public function getList($condition=[],$field='*',$order='id asc',$size=15){
		
		$result=$this->where($condition)->field($field)->order($order)->paginate($size,false,['query' =>input()]);
		if($result){
			foreach ($result as &$item){
				$this->formatSelect($item);
			}
		}
		return $result;
	}
	
	public function deleteVB($condition){
		$result=$this->where($condition)->select();
		if($result){
			foreach($result as $item){
				$this->where(['id'=>$item['id']])->delete();
			}
		}
		return TRUE;
	}
}